package com.moyingren.springcloud.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
public class Upload {
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public Object upload(@RequestParam("photo") MultipartFile photo, HttpServletRequest httpServletRequest) throws IOException {
        Map<String, Object> map = new HashMap<>();
        String filename = "photo";
        if (photo != null) {
            map.put("photo-name", photo.getName());
            map.put("content-type", photo.getContentType());
            map.put("photo-size", photo.getSize());
            filename = UUID.randomUUID() + "." + photo.getContentType().substring(photo.getContentType().indexOf("/") + 1);
            System.out.println("filename:" + filename);
            String filePath = httpServletRequest.getServletContext().getRealPath("/") + filename;
            photo.transferTo(new File(filePath));
            map.put("save-path", filePath);
            map.put("save-file", filename);
        }
        return map;
    }
}
